//
//  ReCommendViewController.m
//  SweetComics
//
//  Created by LeeZhe on 15/1/28.
//  Copyright (c) 2015年 LeeZhe. All rights reserved.
//

#import "ReCommendViewController.h"
#import "UIImageView+WebCache.h"
#import "ComicList.h"
#import "AFHTTPRequestOperationManager.h"
#import "RecommendCollectionViewCell.h"
#import "SecondViewController.h"
#import "DetailViewController.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "TopScrollView.h"
#import "SearchViewController.h"
#import "AppDelegate.h"
#import "ClassifyViewController.h"
#import "RootViewController.h"
//#import "MBProgressHUD.h"
@interface ReCommendViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate,UIAlertViewDelegate>

@property (nonatomic, retain)NSDictionary *dic;
@property (nonatomic, retain)UIScrollView *scrollView;

@property (nonatomic, retain)UIScrollView *scrollViewLittle;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)UIPageControl *pageControl;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)UIImageView *imageView;
@property (nonatomic,retain)ComicList *comicOne;
@property (nonatomic,retain)ComicList *comicTwo;
@property (nonatomic,retain)ComicList *comicThree;
@property (nonatomic, retain)NSMutableArray *arrFour;
@property (nonatomic, retain)MBProgressHUD *progress;
@property (nonatomic,retain)NSMutableArray *comicArr;
@end



@implementation ReCommendViewController

- (void)dealloc
{
    [super dealloc];
    [_dic release];
    [_scrollViewLittle release];
    [_arr release];
    [_pageControl release];
    [_collectionView release];
    [_imageView release];
    [_comicOne release];
    [_comicTwo release];
    [_comicThree release];
    [_arrFour release];
    [_progress release];
    [_comicArr release];
    [_scrollView release];
    
}






- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    self.title = @"推荐";
    [self createView];
    
    [self netWork];
    [self receiveData];
    
}
- (void)receiveData
{
    // 接收第一个 comic ;
    NSNotificationCenter *centerOne = [NSNotificationCenter defaultCenter];
    [centerOne addObserver:self selector:@selector(actionOne:) name:@"One" object:nil];
    
    // 接收第二个 commic
    NSNotificationCenter *centerTwo = [NSNotificationCenter defaultCenter];
    [centerTwo addObserver:self selector:@selector(actionTwo:) name:@"Two" object:nil];
    
    // 接收第三个 comic
    
    NSNotificationCenter *centerThree = [NSNotificationCenter defaultCenter];
    [centerThree addObserver:self selector:@selector(actionThree:) name:@"Three" object:nil];
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-dibudaohangfenlei2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(showMenu)] autorelease];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(barButtonAction1:)]autorelease];
}
-(void)netWork
{
    NSString *str = @"http://mobilev3.ac.qq.com/Classify/categoryList/category_id/50005/listcnt/12/page/1/clientType/0";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self createMbView];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //            NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        NSMutableArray *array = [dic objectForKey:@"data"];
        for (NSDictionary *dicList in array) {
            ComicList *comic = [[ComicList alloc]init];
            [comic setValuesForKeysWithDictionary:dicList];
            [self.arr addObject:comic];
            [self.collectionView reloadData];
            [self.progress hide:YES];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@", error);
        //        [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        imageView.image = [UIImage imageNamed:@"replace.png"];
        [self.view addSubview:imageView];
        imageView.tag = 1;
        [imageView release];
        [self createMbView];
        [_progress hide:YES afterDelay:3];
        
        [NSThread sleepForTimeInterval:4];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有网络\r甜心偷懒了哦" delegate: self cancelButtonTitle:@"联网重试" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }];
}
- (void)createView
{
    NSLog(@"%@",self.navigationController);
    //定义一个最大的scrollView
    self.arr = [NSMutableArray array];
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height + 520)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    // self.scrollView.contentSize = CGSizeMake(0,310+ 1170);
    self.scrollView.contentSize = CGSizeMake(0, self.view.frame.size.height + 820);
    [self.view addSubview:self.scrollView];
    [self topView];
    
    
    
    // 写一个观察者 接收TopView传过来的数组对象
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(actionOne:) name:@"gongpu" object:nil];
    
    
    //下面的collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //flowLayout.itemSize = CGSizeMake(110, 200);
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 3 - 10,self.scrollView.frame.size.height / 6 - 20);
    //    flowLayout.minimumInteritemSpacing = 1;
    //    flowLayout.minimumLineSpacing = 1;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height / 3.787 + 40, self.view.bounds.size.width, self.view.bounds.size.height + 500) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.scrollView addSubview:self.collectionView];
    [self.collectionView release];
    self.collectionView.scrollEnabled = NO;
    
    
    //    self.scrollView.contentSize = CGSizeMake(0, self.view.bounds.size.height / 3 + 40 + ((self.view.frame.size.width - 20) / 3 * 20 / 11 + 40) * 4);
    
    //collectionView的cell需要提前注册
    [self.collectionView registerClass:[RecommendCollectionViewCell class] forCellWithReuseIdentifier:@"suibian"];
    
    
    
    
    
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, self.view.frame.size.height *0.28, self.view.frame.size.width *0.267, 40)];
    label.text = @"精品";
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = [UIColor purpleColor];
    [self.scrollView addSubview:label];
    [label release];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0.1867 * self.view.frame.size.width,self.view.frame.size.height *0.3100,0.64 * self.view.frame.size.width,0.5)];
    
    
    line.backgroundColor = [UIColor orangeColor];
    line.alpha = 0.3;
    [self.scrollView addSubview:line];
    [line release];
    UIImageView *arrowKey = [[UIImageView alloc] init];
    arrowKey.frame = CGRectMake(0.965 * self.view.frame.size.width,self.view.frame.size.height *0.299,0.05 * self.view.frame.size.width,15);
    arrowKey.image = [UIImage imageNamed:@"箭头"];
    arrowKey.alpha = 0.3;
    [self.scrollView addSubview:arrowKey];
    [arrowKey release];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake(0.86 * self.view.frame.size.width,self.view.frame.size.height *0.28,0.1 * self.view.frame.size.width,40);
    button1.titleLabel.textColor = [UIColor darkGrayColor];
    button1.titleLabel.font = [UIFont systemFontOfSize:16];
    [button1 setTitle:@"全部" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(buttonClicked1:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:button1];
    
}
- (void)createMbView
{
    self.progress = [[[MBProgressHUD alloc]initWithView:self.view]autorelease];
    self.progress.labelFont = [UIFont systemFontOfSize:10];
    self.progress.labelText = @"努力加载中";
    [self.progress show:YES ];
    [self.view addSubview:_progress];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    ReCommendViewController *recomendVC = [[ReCommendViewController alloc] init];
    [self.navigationController pushViewController:recomendVC animated:YES];
    [recomendVC release];
}

- (void)actionOne:(NSNotification *)notify
{
    self.comicOne = [[ComicList alloc] init];
    self.comicOne = notify.object;
    [_comicOne release];
}
- (void)actionTwo:(NSNotification *)notify
{
    self.comicTwo = [[ComicList alloc] init];
    self.comicTwo = notify.object;
    [_comicTwo release];
}
- (void)actionThree:(NSNotification *)notify
{
    self.comicThree = [[ComicList alloc] init];
    self.comicThree = notify.object;
    [_comicThree release];
}



- (void)topView
{
    TopScrollView *topView = [[TopScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.bounds.size.height / 3.587)];
    [topView createView];
    
    [self.scrollView addSubview:topView];
    for (NSInteger i = 0; i < 3; i++ ) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(self.view.frame.size.width * i,0, self.view.frame.size.width, self.view.bounds.size.height / 3.787);
        button.tag = i + 1;
        [topView.scrollViewLittle addSubview:button];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
    [topView release];
    
}







//最上面的scrollView的点击方法
- (void)buttonClicked:(UIButton *)button
{
    self.comicArr = [NSMutableArray arrayWithObjects:_comicOne,_comicTwo,_comicThree,nil];
    for (NSInteger i = 0 ; i < self.comicArr.count; i++) {
        if (button.tag == i + 1) {
            DetailViewController *detailVC = [[DetailViewController alloc] init];
            [self.navigationController pushViewController:detailVC animated:YES];
            detailVC.comic = [self.comicArr objectAtIndex:i];
            [detailVC release];
        }
        
    }
}

//全部的点击方法
- (void)buttonClicked1:(UIButton *)button
{
    SecondViewController *second = [[SecondViewController alloc]init];
    [self.navigationController pushViewController:second animated:YES];
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RecommendCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"suibian" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    
    ComicList *comic = [self.arr objectAtIndex:indexPath.row];
    cell.label.text = comic.title;
    
    [cell setComicList:comic];
    cell.label1.text = comic.lastup;
    return cell;
}

//collectionView点击进入详情页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detail = [[DetailViewController alloc]init];
    
    detail.comic = [self.arr objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:detail animated:YES];
}



-(void)showPageControl
{
    _pageControl.numberOfPages = 3;
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor greenColor];
    [_scrollView addSubview:_pageControl];
    
}

- (void)ChangeContentoffset
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(change) userInfo:nil repeats:YES];
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    [runloop addTimer:timer forMode:NSDefaultRunLoopMode];
    [timer fire];
}

- (void)change
{
    _scrollViewLittle.contentOffset = CGPointMake(_scrollViewLittle.contentOffset.x + _scrollViewLittle.frame.size.width * _flag, 0);
    _flag++;
    if (_flag == 2) {
        _flag = 1;
    }
    
    if (_scrollViewLittle.contentOffset.x == self.view.frame.size.width*3) {
        _scrollViewLittle.contentOffset = CGPointMake(0, 0);
    }
    
}

- (void)ChangeContentoffsetAction1:(NSTimer *)timer
{
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = self.scrollViewLittle.contentOffset.x / self.scrollViewLittle.frame.size.width;
    self.pageControl.currentPage = page;
}
#pragma mark -
#pragma mark Button actions

- (void)showMenu
{
    if (!_sideMenu) {
        RESideMenuItem *itemWithSubItems0 = [[RESideMenuItem alloc] initWithTitle:@"分类列表" action:^(RESideMenu *menu, RESideMenuItem *item) {
            
        }];
        
        RESideMenuItem *homeItem = [[RESideMenuItem alloc]initWithTitle:@"青春往事" image:[UIImage imageNamed:@"5.gif" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            
            ClassifyViewController *qingChunVC = [[ClassifyViewController alloc] init];
            qingChunVC.title = item.title;
            qingChunVC.comicId = @"7";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:qingChunVC];
            
            [menu setRootViewController:navigationController];
            
        }];
        
        
        RESideMenuItem *exploreItem = [[RESideMenuItem alloc] initWithTitle:@"玄幻" image:[UIImage imageNamed:@"2.jpg" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            ClassifyViewController *xuanHuanVC = [[ClassifyViewController alloc] init];
            xuanHuanVC.title = item.title;
            xuanHuanVC.comicId = @"13";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:xuanHuanVC];
            
            [menu setRootViewController:navigationController];
            
        }];
        
        RESideMenuItem *activityItem = [[RESideMenuItem alloc] initWithTitle:@"热血" image:[UIImage imageNamed:@"1.jpg" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            
            ClassifyViewController *reXueVC = [[ClassifyViewController alloc] init];
            reXueVC.title = item.title;
            reXueVC.comicId = @"3";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:reXueVC];
            
            [menu setRootViewController:navigationController];
            
        }];
        //            [menu hide];
        RESideMenuItem *profileItem = [[RESideMenuItem alloc] initWithTitle:@"搞笑" image:[UIImage imageNamed:@"7.png" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            ClassifyViewController *gaoXiaoVC = [[ClassifyViewController alloc] init];
            gaoXiaoVC.title = item.title;
            gaoXiaoVC.comicId = @"1";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:gaoXiaoVC];
            
            [menu setRootViewController:navigationController];
            
        }];
        RESideMenuItem *aroundMeItem = [[RESideMenuItem alloc] initWithTitle:@"恐怖" image:[UIImage imageNamed:@"4.jpg" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            ClassifyViewController *kongBuVC = [[ClassifyViewController alloc] init];
            kongBuVC.title = item.title;
            kongBuVC.comicId = @"2";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:kongBuVC];
            
            [menu setRootViewController:navigationController];
            
        }];
        RESideMenuItem *helpPlus1 = [[RESideMenuItem alloc] initWithTitle:@"热门改编" image:[UIImage imageNamed:@"6.jpg" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            ClassifyViewController *gaiBianVC = [[ClassifyViewController alloc] init];
            gaiBianVC.title = item.title;
            gaiBianVC.comicId = @"14";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:gaiBianVC];
            
            [menu setRootViewController:navigationController];
        }];
        RESideMenuItem *helpPlus2 = [[RESideMenuItem alloc] initWithTitle:@"美少女" image:[UIImage imageNamed:@"3.jpg" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            ClassifyViewController *meiVC = [[ClassifyViewController alloc] init];
            meiVC.title = item.title;
            meiVC.comicId = @"11";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:meiVC];
            
            [menu setRootViewController:navigationController];
        }];
        
        RESideMenuItem *helpCenterItem = [[RESideMenuItem alloc] initWithTitle:@"恋爱" image:[UIImage imageNamed:@"0.jpg" ] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            ClassifyViewController *lianAiVC = [[ClassifyViewController alloc] init];
            lianAiVC.title = item.title;
            lianAiVC.comicId = @"9";
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:lianAiVC];
            
            [menu setRootViewController:navigationController];
        }];
        
        RESideMenuItem *itemWithSubItems = [[RESideMenuItem alloc] initWithTitle:@"GO BACK >>" action:^(RESideMenu *menu, RESideMenuItem *item) {
            RootViewController *rootVC = [[RootViewController alloc] init];
            [menu setRootViewController:rootVC];
        }];
        _sideMenu = [[RESideMenu alloc] initWithItems:@[itemWithSubItems0,homeItem, exploreItem, activityItem, profileItem,aroundMeItem, helpPlus1, helpPlus2, helpCenterItem,itemWithSubItems]];
        _sideMenu.verticalOffset = IS_WIDESCREEN ?  : 20;
        _sideMenu.hideStatusBarArea = [AppDelegate OSVersion] < 9;
    }
    
    [_sideMenu show];
}

// 搜索按钮
- (void)barButtonAction1:(UIBarButtonItem *)button
{
    self.hidesBottomBarWhenPushed = YES;
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:NO];
    self.hidesBottomBarWhenPushed = NO;
    [searchVC release];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
